package yb.ecp.fast.user.service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.infra.util.StringUtil;
import yb.ecp.fast.user.dao.entity.*;
import yb.ecp.fast.user.dao.mapper.*;
import yb.ecp.fast.user.infra.AuthConstant;
import yb.ecp.fast.user.infra.ErrorCode;
import yb.ecp.fast.user.service.VO.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LiChangjiang on 2017/12/27 0027.
 */
@Service
public class TemplateService
{
    @Autowired
    TemplateMapper templateMapper;

    @Autowired
    TmpAuthMapper tmpAuthMapper;

    @Autowired
    TmpMenuMapper tmpMenuMapper;

    @Autowired
    ProfileMapper profileMapper;

    @Autowired
    WorkspaceMapper workspaceMapper;

    @Autowired
    MenuService menuService;

    @Autowired
    AuthService authService;


    public List<TemplateVO> queryList()
    {
        List<TemplateDO> templateDOs;
        List<TemplateVO> templateVOs = new ArrayList<>();

        templateDOs = templateMapper.queryList();

        for (TemplateDO templateDO : templateDOs)
        {
            //权限模板列表不展示管理端权限模板信息
            if(templateDO.getId().equals(AuthConstant.TEMPLATE_ID_MANAGER))
            {
                continue;
            }
            TemplateVO templateVO = new TemplateVO();
            BeanUtils.copyProperties(templateDO, templateVO);
            templateVOs.add(templateVO);
        }
        return templateVOs;
    }

    /**
     * 新增一个权限模板
     *
     * @param templateVO TemplateVO
     * @return ErrorCode
     */
    public ErrorCode insert(TemplateVO templateVO)
    {
        TemplateDO templateDO = new TemplateDO();

        BeanUtils.copyProperties(templateVO, templateDO);

        int ret = templateMapper.insert(templateDO);

        if (0 >= ret)
        {
            LogHelper.error("新增权限模板操作失败！", ErrorCode.FailedToInsertRecord.getCode());
            return ErrorCode.FailedToInsertRecord;
        }

        return ErrorCode.Success;
    }

    /**
     * 根据ID查询模板信息
     *
     * @param id String
     * @return TemplateVO
     */
    public TemplateVO selectById(String id)
    {
        TemplateVO templateVO = new TemplateVO();
        TemplateDO templateDO = templateMapper.selectById(id);
        if(null==templateDO)
        {
            LogHelper.debug(id+"权限模板信息不存在！");
            return  null;
        }
        BeanUtils.copyProperties(templateDO, templateVO);

        return templateVO;
    }

    /**
     * 修改模板信息
     *
     * @param templateVO TemplateVO
     * @return ErrorCode
     */
    public ErrorCode update(TemplateVO templateVO)
    {
        TemplateDO templateDO = new TemplateDO();
        BeanUtils.copyProperties(templateVO, templateDO);

        int ret = templateMapper.updateById(templateDO);
        if (0 >= ret)
        {
            LogHelper.error("修改权限模板操作失败！",ErrorCode.FailedToUpdateRecord.getCode());
            return ErrorCode.FailedToUpdateRecord;
        }

        return ErrorCode.Success;
    }

    /**
     * 批量删除模板
     *
     * @param ids List
     * @return ErrorCode
     */
    public ErrorCode removeByIds(List<String> ids,Ref<List> tmpRef)
    {
        List<String> templateNames = checkTempDeleteCondition(ids);

        if(!ListUtil.isNullOrEmpty(templateNames))
        {
            tmpRef.set(templateNames);
            return ErrorCode.TemplateInUse;
        }

        for (String id : ids)
        {
           templateMapper.removeById(id);
            // 删除模板对应的权限和menu

            tmpAuthMapper.removeByTemplate(id);
            tmpMenuMapper.removeByTemplate(id);
        }
        return ErrorCode.Success;
    }

    private List<String> checkTempDeleteCondition(List<String> ids)
    {
        List<String> templateNames = new ArrayList<>();
        for (String id : ids)
        {
           int ret =  workspaceMapper.queryCountByTempId(id);
            if(0<ret)
            {
                LogHelper.debug(id+"权限模板没有被释放，无法删除！");
                templateNames.add(selectById(id).getName());
            }
        }
        return templateNames;
    }



    /**
     * 给模板配置权限
     *
     * @param tmpAuthsVO TmpAuthsVO
     * @return ErrorCode
     */
    public ErrorCode configTmpAuth(TmpAuthsVO tmpAuthsVO)
    {
        List<Integer> auths = tmpAuthsVO.getAuthIds();

        for (Integer authId : auths)
        {
            TmpAuthDO tmpAuthDO = new TmpAuthDO();
            tmpAuthDO.setAuthId(authId);
            tmpAuthDO.setTmpId(tmpAuthsVO.getTemplateId());

            tmpAuthMapper.insert(tmpAuthDO);
        }
        return ErrorCode.Success;
    }

    /**
     * 配置权限模板信息
     * @param templateConfigVO TemplateConfigVO
     * @return ErrorCode
     */
    public ErrorCode configTemplate(TemplateConfigVO templateConfigVO)
    {
        List<Integer> auths = templateConfigVO.getAuthIds();
        List<Integer> menuIds = templateConfigVO.getMenuIds();


        tmpAuthMapper.removeByTemplate(templateConfigVO.getTempId());
        if (!ListUtil.isNullOrEmpty(auths))
        {
            for (Integer authId : auths)
            {
                TmpAuthDO tmpAuthDO = new TmpAuthDO();
                tmpAuthDO.setAuthId(authId);
                tmpAuthDO.setTmpId(templateConfigVO.getTempId());

                tmpAuthMapper.insert(tmpAuthDO);
            }
        }

        tmpMenuMapper.removeByTemplate(templateConfigVO.getTempId());
        if (!ListUtil.isNullOrEmpty(menuIds))
        {
            for (Integer menuId : menuIds)
            {
                TmpMenuDO tmpMenuDO = new TmpMenuDO();
                tmpMenuDO.setMenuId(menuId);
                tmpMenuDO.setTmpId(templateConfigVO.getTempId());

                tmpMenuMapper.insert(tmpMenuDO);
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 查询模板对应的权限集合
     *
     * @param tmpId Integer
     * @return List
     */
    public List<Integer> queryAuthByTemplate(String tmpId)
    {
        return tmpAuthMapper.queryList(tmpId);
    }

    /**
     * 移除模板下的所有权限
     *
     * @param tmpId Integer
     * @return ErrorCode
     */
    public ErrorCode removeAuthByTemplate(String tmpId)
    {
        tmpAuthMapper.removeByTemplate(tmpId);
        return ErrorCode.Success;
    }

    /**
     * 移除模板下的权限
     *
     * @param tmpAuthsVO TmpAuthsVO
     * @return ErrorCode
     */
    public ErrorCode removeAuths(TmpAuthsVO tmpAuthsVO)
    {
        List<Integer> auths = tmpAuthsVO.getAuthIds();

        for (Integer authId : auths)
        {
            TmpAuthDO tmpAuthDO = new TmpAuthDO();
            tmpAuthDO.setAuthId(authId);
            tmpAuthDO.setTmpId(tmpAuthsVO.getTemplateId());

            tmpAuthMapper.removeAuth(tmpAuthDO);
        }
        return ErrorCode.Success;
    }


    /**
     * 给模板配置Menu
     *
     * @param tmpMenusVO TmpMenusVO
     * @return ErrorCode
     */
    public ErrorCode configTmpMenu(TmpMenusVO tmpMenusVO)
    {
        List<Integer> menuIds = tmpMenusVO.getMenuIds();

        if(StringUtil.isNullOrEmpty(tmpMenusVO.getTemplateId()))
        {
            LogHelper.error("权限模板ID为空！",ErrorCode.TemplateIsNull.getCode());
            return ErrorCode.TemplateIsNull;
        }

        for (Integer menuId : menuIds)
        {
            TmpMenuDO tmpMenuDO = new TmpMenuDO();
            tmpMenuDO.setMenuId(menuId);
            tmpMenuDO.setTmpId(tmpMenusVO.getTemplateId());

            tmpMenuMapper.insert(tmpMenuDO);
        }
        return ErrorCode.Success;
    }

    /**
     * 查询模板对应的Menu集合
     *
     * @param tmpId String
     * @return List
     */
    public List<Integer> queryMenuByTemplate(String tmpId)
    {
        return tmpMenuMapper.queryList(tmpId);
    }

    /**
     * 查询模板配置信息（权限code集合&menu集合）
     * @param tmpId String
     * @return TemplateConfigVO
     */
    public TemplateConfigVO queryTemplateConfigById(String tmpId)
    {
        TemplateConfigVO templateConfigVO = new TemplateConfigVO();
       List<Integer> menus =  tmpMenuMapper.queryList(tmpId);
       List<Integer> auths =  tmpAuthMapper.queryList(tmpId);

        templateConfigVO.setTempId(tmpId);
        templateConfigVO.setAuthIds(auths);
        templateConfigVO.setMenuIds(menus);
        return templateConfigVO;
    }

    /**
     * 移除模板下的所有Menu
     *
     * @param tmpId Integer
     * @return ErrorCode
     */
    public ErrorCode removeMenuByTemplate(String tmpId)
    {
        tmpMenuMapper.removeByTemplate(tmpId);
        return ErrorCode.Success;
    }

    /**
     * 移除模板下的Menu
     *
     * @param tmpMenusVO TmpMenusVO
     * @return ErrorCode
     */
    public ErrorCode removeMenus(TmpMenusVO tmpMenusVO)
    {
        List<Integer> Menus = tmpMenusVO.getMenuIds();

        for (Integer menu : Menus)
        {
            TmpMenuDO tmpMenuDO = new TmpMenuDO();
            tmpMenuDO.setMenuId(menu);
            tmpMenuDO.setTmpId(tmpMenusVO.getTemplateId());

            tmpMenuMapper.removeMenu(tmpMenuDO);
        }
        return ErrorCode.Success;
    }

    /**
     * 获取用户所在的工作空间的权限模板
     * @param userId String
     * @return TemplateVO
     */
    public TemplateVO queryTempByUserId(String userId)
    {
        ProfileDO profileDO = profileMapper.selectById(userId);

        if (null == profileDO)
        {
            LogHelper.debug(userId+"用户信息不存在！");
            return null;
        }

        WorkspaceDO workspaceDO = workspaceMapper.selectById(profileDO.getSpaceId());

        if (null == workspaceDO)
        {
            LogHelper.debug(profileDO.getSpaceId()+"工作空间信息不存在！");
            return null;
        }
        return this.selectById(workspaceDO.getTempId());
    }
}
